<template>
  <div class="settings-container">
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <h3>Account Settings</h3>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="settings-form"
      >
        <el-form-item label="Security Level">
          <el-rate
            v-model="securityLevel"
            :colors="colors"
            :max="3"
            disabled
            show-score
            text-color="#ff9900"
            score-template="{value}"
          ></el-rate>
          <div class="security-tips">
            <el-alert
              :title="securityTips[securityLevel - 1]"
              :type="securityLevel === 3 ? 'success' : 'warning'"
              show-icon
            ></el-alert>
          </div>
        </el-form-item>

        <el-form-item label="Two-Factor Auth" prop="twoFactorAuth">
          <el-switch
            v-model="form.twoFactorAuth"
            active-text="Enabled"
            inactive-text="Disabled"
            @change="handleTwoFactorChange"
          ></el-switch>
        </el-form-item>

        <el-form-item label="Login Notification" prop="loginNotification">
          <el-switch
            v-model="form.loginNotification"
            active-text="Enabled"
            inactive-text="Disabled"
          ></el-switch>
        </el-form-item>

        <el-form-item label="Account Binding">
          <div class="binding-list">
            <div class="binding-item">
              <span class="binding-icon">
                <el-icon><Message /></el-icon>
              </span>
              <span class="binding-info">
                <strong>Email</strong>
                <span v-if="userStore.user.email">{{ userStore.user.email }}</span>
                <span v-else class="not-bound">Not Bound</span>
              </span>
              <el-button
                :type="userStore.user.email ? 'danger' : 'primary'"
                link
                @click="handleEmailBinding"
              >
                {{ userStore.user.email ? 'Unbind' : 'Bind' }}
              </el-button>
            </div>

            <div class="binding-item">
              <span class="binding-icon">
                <el-icon><Iphone /></el-icon>
              </span>
              <span class="binding-info">
                <strong>Phone</strong>
                <span v-if="userStore.user.phone">{{ userStore.user.phone }}</span>
                <span v-else class="not-bound">Not Bound</span>
              </span>
              <el-button
                :type="userStore.user.phone ? 'danger' : 'primary'"
                link
                @click="handlePhoneBinding"
              >
                {{ userStore.user.phone ? 'Unbind' : 'Bind' }}
              </el-button>
            </div>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSave" :loading="loading">
            Save Settings
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- Account deactivation card -->
    <el-card class="settings-card danger-zone" style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <h3>Danger Zone</h3>
        </div>
      </template>

      <div class="danger-zone-content">
        <div class="danger-item">
          <div class="danger-info">
            <h4>Deactivate Account</h4>
            <p>After deactivation, your account will be permanently deleted and all data will be unrecoverable.</p>
          </div>
          <el-button type="danger" @click="handleDeactivate">Deactivate Account</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Message, Iphone } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'

const userStore = useUserStore()
const formRef = ref<FormInstance>()
const loading = ref(false)

// Form data
const form = reactive({
  twoFactorAuth: false,
  loginNotification: true
})

// Form validation rules
const rules = {
  twoFactorAuth: [
    { required: true, message: 'Please select whether to enable two-factor authentication', trigger: 'change' }
  ],
  loginNotification: [
    { required: true, message: 'Please select whether to enable login notification', trigger: 'change' }
  ]
}

// Security level related
const securityLevel = ref(1)
const colors = ['#F56C6C', '#E6A23C', '#67C23A']
const securityTips = [
  'Your account security level is low, it is recommended to enable two-factor authentication and login notification',
  'Your account security level is medium, consider binding your phone or email',
  'Your account security level is high, please maintain it'
]

// Calculate security level
const calculateSecurityLevel = () => {
  let level = 1
  if (form.twoFactorAuth) level++
  if (form.loginNotification) level++
  securityLevel.value = Math.min(level, 3)
}

// Handle two-factor authentication change
const handleTwoFactorChange = (value: boolean) => {
  if (value) {
    // TODO: Implement two-factor authentication setup process
    ElMessage.info('Two-factor authentication coming soon')
  }
  calculateSecurityLevel()
}

// Handle email binding
const handleEmailBinding = async () => {
  if (userStore.user.email) {
    // Unbind email
    try {
      await ElMessageBox.confirm('Are you sure you want to unbind your email?', 'Confirmation', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      })
      // TODO: Call email unbinding API
      ElMessage.success('Email unbound successfully')
    } catch (error) {
      // User canceled operation
    }
  } else {
    // TODO: Implement email binding process
    ElMessage.info('Email binding coming soon')
  }
}

// Handle phone binding
const handlePhoneBinding = async () => {
  if (userStore.user.phone) {
    // Unbind phone
    try {
      await ElMessageBox.confirm('Are you sure you want to unbind your phone?', 'Confirmation', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      })
      // TODO: Call phone unbinding API
      ElMessage.success('Phone unbound successfully')
    } catch (error) {
      // User canceled operation
    }
  } else {
    // TODO: Implement phone binding process
    ElMessage.info('Phone binding coming soon')
  }
}

// Save settings
const handleSave = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // TODO: Call save settings API
        ElMessage.success('Settings saved successfully')
      } catch (error: any) {
        ElMessage.error(error.response?.data?.message || 'Failed to save settings')
      } finally {
        loading.value = false
      }
    }
  })
}

// Deactivate account
const handleDeactivate = async () => {
  try {
    await ElMessageBox.confirm(
      'Deactivating your account is irreversible, and all your data will be permanently deleted. Please enter your password to confirm:',
      'Warning',
      {
        confirmButtonText: 'Confirm Deactivation',
        cancelButtonText: 'Cancel',
        type: 'error',
        showInput: true,
        inputType: 'password',
        inputPlaceholder: 'Enter your password'
      }
    )
    // TODO: Call account deactivation API
    ElMessage.success('Account deactivated')
    userStore.logout()
  } catch (error) {
    // User canceled operation
  }
}
</script>

<style scoped>
.settings-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.settings-card {
  background-color: #fff;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.settings-form {
  margin-top: 20px;
}

.security-tips {
  margin-top: 10px;
}

.binding-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.binding-item {
  display: flex;
  align-items: center;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.binding-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  background-color: #e6e8eb;
  border-radius: 50%;
  margin-right: 12px;
}

.binding-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.not-bound {
  color: #909399;
  font-size: 13px;
}

.danger-zone {
  border: 1px solid #f56c6c;
}

.danger-zone .card-header {
  border-bottom-color: #f56c6c;
}

.danger-zone-content {
  padding: 16px 0;
}

.danger-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: #fff5f5;
  border-radius: 4px;
}

.danger-info h4 {
  margin: 0 0 8px 0;
  color: #f56c6c;
}

.danger-info p {
  margin: 0;
  font-size: 14px;
  color: #666;
}
</style> 